<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * PENGUIN FrameWork
 * Tự động add module resource cho FW
 * Add file / database
 * 
 * @author      hungtd <tdhungit@gmail.com> 0972014011
 * @copyright   Tran Dinh Hung 2011
 * @package     PenguinFW
 * @subpackage  ModuelBuilder
 * @version     1.0.0
 */

class Module_builder extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper('date');
    }
    
    public function index()
    {                
        $this->load->helper('form');
        $this->load->library('form_validation');        
        
        $this->form_validation->set_rules('module', 'Module', 'required');
		$this->form_validation->set_rules('module_resource', 'Module resource', 'required');
        $this->form_validation->set_rules('username', 'Username', 'required');
        
        $error_message = '';                
                
        if ($this->form_validation->run() == TRUE) 
        {
            // get data from form
            $module = $this->input->post('module');
            $module_resource = $this->input->post('module_resource');
            $module_resource_main = $this->input->post('module_resource_main');
            $username = $this->input->post('username');
            
            $new_module = $this->input->post('new_module');
            $new_resource = $this->input->post('new_resource');
            
            $insert_menu = $this->input->post('insert_menu');
            $menu_link_tmp = $this->input->post('menu_link');            
            
            $insert_field = $this->input->post('insert_field');
            $fields = $this->input->post('field_name');                        
            
            // check data require
            if (!$module || !$module_resource || !$username) 
            {                
                show_error(lang('Please input field require (module, module resource, username)'));
            }
            
            if ($new_resource == 1 && $insert_field == 1 && !$module_resource_main) 
            {
                if (empty ($fields) || !in_array('created', $fields) || !in_array('modified', $fields) || !in_array('user_id', $fields)) 
                {
                    show_error(lang('Please input field require (created, modified, user_id)'));
                }
            }
            
            // change char to lower
            $module_m = strtolower($module);
            $module_name = $module_m . 's';
            $module_r = strtolower($module_resource);
            $username = strtolower($username);
            
            // get menu link
            $menu_link = ($menu_link_tmp) ? $menu_link_tmp : '/' . $module_r;

            // check username 
            $dbqueryuser = $this->db->get_where('users', array('username' => $username));
            if ($dbqueryuser->num_rows() == 0) show_error (lang('Username not exit.'));
            $dbuser = $dbqueryuser->row();
            
            // query check module
            $this->db->select('id');                
            $dbmodule = $this->db->get_where('modules', array('name' => $module_name));
            
            // check condition and module
            if ($new_module != 1 && $dbmodule->num_rows() == 0) show_error (lang('Module not exit.'));
            
            // module not exit -> insert module to database
            if ($dbmodule->num_rows() == 0) 
            {
                $dbmodule_data = array(
                    'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'name' => $module_name,
                    'user_id' => $dbuser->id
                );
                $this->db->insert('modules', $dbmodule_data);
                // get id module
                $dbmodule_id = $this->db->insert_id();
            } else $dbmodule_id = $dbmodule->row()->id;
            
            // check insert module
            if (!$dbmodule_id) show_error (lang('Insert module error.'));
            
            // check resource
            $this->db->select('id');
            $dbresource = $this->db->get_where('module_resources', array('name' => $module_r));
            
            // check resource and conditions
            if ($new_resource != 1 && $dbresource->num_rows() == 0) show_error (lang('Resource not exit.'));
            
            // check main resource
            $this->db->select('id');
            $dbmainresource = $this->db->get_where('module_resources', array('name' => $module_resource_main));
            $resource_main_id = ($dbmainresource->num_rows() == 0) ? 0 : $dbmainresource->row()->id;
            
            // resource not exit -> insert database
            if ($dbresource->num_rows() == 0) 
            {
                $dbresource_data = array(
                    'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'name' => $module_r,
                    'main_id' => $resource_main_id,
                    'module_id' => $dbmodule_id,
                    'user_id' => $dbuser->id
                );
                $this->db->insert('module_resources', $dbresource_data);
                
                // get resource id
                $dbresource_id = $this->db->insert_id();
            } else $dbresource_id = $dbresource->row()->id;
            
            // check insert module resource
            if (!$dbresource_id) show_error (lang('Insert module resource error.'));
            
            // check insert menu
            if ($insert_menu == 1) 
            {
                $menu_data = array(
                    'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                    'name' => $module,
                    'link' => $menu_link,
                    'user_id' => $dbuser->id
                );
                
                $this->db->insert('menus', $menu_data);
            }
            
            // check insert field and custom field
            if ($insert_field == 1) 
            {
                // check custom field name
                $this->db->select('id');
                $dbcustomfield = $this->db->get_where('custom_field_names', array('name' => ConstCustomField::defaultName, 'resource_id' => $dbresource_id));
                $cfn_is_exit = $dbcustomfield->num_rows();

                // if not exit -> create it
                if ($cfn_is_exit == 0) {
                    $cf_name_data = array(
                        'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                        'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                        'name' => ConstCustomField::defaultName,
                        'share' => ConstCustomField::all,
                        'resource_id' => $dbresource_id,
                        'user_id' => $dbuser->id
                    );

                    $this->db->insert('custom_field_names', $cf_name_data);

                    // custom field name id
                    $cf_name_id = $this->db->insert_id();

                    // field default to insert custom field name default
                    $default_field = array(
                        'created',
                        'name',
                        'link',
                        'weight',
                        'point'
                    );
                } // // if not exit -> create it

                // check and insert fields
                $f = 0;
                foreach ($fields as $field) 
                {
                    $f++;
                    if ($field == 'created' || $field == 'modified') 
                    {
                        $field_name = $field;
                        $field_type = ConstFieldType::datetime;
                    } else if ($field == 'user_id') 
                    {
                        $field_name = $field;
                        $field_type = ConstFieldType::num;
                    } else 
                    {
                        $field_array = explode('|', $field);
                        $field_name = $field_array[0];
                        if ($field_array[2])
                            $field_type = $field_array[2];
                        else
                            $field_type = ConstFieldType::text;
                    }

                    // insert module field
                    $field_data = array(
                        'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                        'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                        'name' => $field_name,
                        'field_type' => $field_type,
                        'weight' => $f,
                        'resource_id' => $dbresource_id,
                        'user_id' => $dbuser->id
                    );

                    $this->db->insert('module_fields', $field_data);                    
                    $field_id = $this->db->insert_id();

                    // insert custom field default
                    if ($cfn_is_exit == 0) 
                    {
                        if ($cf_name_id) 
                        {
                            if (in_array($field_name, $default_field)) 
                            {
                                $custom_field_name_data = array(
                                    'created' => mdate('%Y-%m-%d %H:%i:%s', now()),
                                    'modified' => mdate('%Y-%m-%d %H:%i:%s', now()),
                                    'name_id' => $cf_name_id,
                                    'field_id' => $field_id,
                                    'user_id' => $dbuser->id
                                );

                                $this->db->insert('custom_fields', $custom_field_name_data);
                            }
                        }
                    } // // insert custom field default
                } // // end foreach
            } // // check insert field and custom field

            // add folder and class file
            @mkdir(str_replace('system/', '', BASEPATH) . 'application/modules/'.$module_name.'/controllers', 0775, true);
            @mkdir(str_replace('system/', '', BASEPATH) . 'application/modules/'.$module_name.'/models', 0775, true);
            @mkdir(str_replace('system/', '', BASEPATH) . 'application/views/'.config_item('penguin_theme').'/'.$module_name, 0775, true);

            if ($new_resource == 1)
                $cf = @fopen(str_replace('system/', '', BASEPATH) . 'application/modules/'.$module_name.'/controllers/'.$module_r.'.php', 'w');

            $cs = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * PENGUIN FrameWork
 * @author hungtd <tdhungit@gmail.com> 0972014011
 * @copyright Tran Dinh Hung 2011
 * 
 * Controller $module_resource
 * ...
 * 
 * @package PenguinFW
 * @subpackage $module
 * @version 1.0.0
 */
 
class $module_resource extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
            
        \$this->model_name = '$module';
                
        \$this->lang->load('generate', config_item('language'));
        \$this->lang->load('".$module_m."', config_item('language'));
            
        \$this->load->model('$module');
    }
}
                
?>";
            if ($new_resource == 1) 
            {
                fwrite($cf, $cs);
                fclose($cf);                                
            }

            if ($new_module == 1)
                $mf = @fopen(str_replace('system/', '', BASEPATH) . 'application/modules/'.$module_name.'/models/'.$module_m.'.php', 'w');

            $ms = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * PENGUIN FrameWork
 * @author hungtd <tdhungit@gmail.com> 0972014011
 * @copyright Tran Dinh Hung 2011
 * 
 * Model
 * Function on $module
 * 
 * @package PenguinFW
 * @subpackage $module
 * @version 1.0.0
 */

class $module extends MY_Model
{
    function __construct()
    {
        parent::__construct();
        
        \$this->db_table = '$module_name';
    }
}

?>";
            if ($new_module == 1)
            {
                fwrite($mf, $ms);
                fclose($mf);             
            }
        }
        
        //echo '<pre>'; print_r($this->input->post());
        //echo str_replace('system/', '', BASEPATH);
        
        $data = array();
        
        $this->load->view('module_builder.php', $data);
    }
}

?>
